//
//  GT_Tool.m
//  GTElectron
//
//  Created by 小蜜蜂 on 14-3-18.
//  Copyright (c) 2014年 chou. All rights reserved.
//

#import "GT_Tool.h"
//#import "SSKeychain.h"
#import "Reachability.h"

@implementation GT_Tool

#define DEFAULT_VOID_COLOR 0

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

+ (UIColor *) colorWithHexString: (NSString *) stringToConvert
{
	NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:
						  [NSCharacterSet whitespaceAndNewlineCharacterSet]]
						 uppercaseString];
	
	// String should be 6 or 8 characters
	if ([cString length] < 6) return DEFAULT_VOID_COLOR;
	
	// strip 0X if it appears
	if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
	
    NSRange myrange = [cString rangeOfString:@"#"];
    if (myrange.location != NSNotFound)
    {
        cString = [cString substringFromIndex:1];
    }
	if ([cString length] != 6) return DEFAULT_VOID_COLOR;
	// Separate into r, g, b substrings
	NSRange range;
	range.location = 0;
	range.length = 2;
	NSString *rString = [cString substringWithRange:range];
	
	range.location = 2;
	NSString *gString = [cString substringWithRange:range];
	
	range.location = 4;
	NSString *bString = [cString substringWithRange:range];
	// Scan values
	unsigned int r, g, b;
	[[NSScanner scannerWithString:rString] scanHexInt:&r];
	[[NSScanner scannerWithString:gString] scanHexInt:&g];
	[[NSScanner scannerWithString:bString] scanHexInt:&b];
	
	return [UIColor colorWithRed:((float) r / 255.0f)
						   green:((float) g / 255.0f)
							blue:((float) b / 255.0f)
						   alpha:1.0f];
}

+ (NSString *)sendJson:(NSMutableDictionary *)dictionary
{
    NSMutableString *jsonText = [[NSMutableString alloc] initWithString:@"{"];
    for (id key in dictionary)
    {
        [jsonText appendFormat:@"\"%@\":\"%@\",",key,[dictionary objectForKey:key]];
    }
    NSString *str = [jsonText substringToIndex:jsonText.length - 1];

    str = [NSString stringWithFormat:@"%@}",str];
    return str;
}

+ (float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
    return sizeToFit.height+5;
}


+ (float) widthForString:(NSString *)value fontSize:(float)fontSize andHeitht:(float)height
{
    CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(CGFLOAT_MAX, height) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
    return sizeToFit.width;
}

+ (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

+ (NSString *)FormatDate:(NSString *)timeStr
{
    if (timeStr == nil)
    {
        return nil;
    }
    
    NSRange range = [timeStr rangeOfString:@" "];
    if (range.location != NSNotFound)
    {
        timeStr = [timeStr substringToIndex:range.location];
    }
    
    return timeStr;
}

//+ (NSString *)uuid
//{
//    //查看keychain中是否存在uuid
//    //获取程序唯一标识
//    NSString *executableFile = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey];
//    
//    NSString *strUUID = [SSKeychain passwordForService:executableFile account:@"UUID"];
//    
//    if (strUUID == nil)
//    {
//        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
//        strUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef));
//        [SSKeychain setPassword:strUUID forService:executableFile account:@"UUID"];
//    }
//    NSLog(@"strUUID:%@",strUUID);
//    return [strUUID stringByReplacingOccurrencesOfString:@"-" withString:@""];
//}

+ (BOOL)isExistenceNetwork
{
    BOOL isExistenceNetwork = NO;
    //Reachability *rr = [Reachability reachabilityForInternetConnection];
	Reachability *r = [Reachability reachabilityWithHostName:@"www.gov.cn"];
    switch ([r currentReachabilityStatus])
	{
        case NotReachable:
			isExistenceNetwork = NO;
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            break;
    }
	if (!isExistenceNetwork)
	{
		NSLog(@"no net");
	}
	return isExistenceNetwork;
}

//
+ (NSString *)encode:(NSString *)_interStr{
	if (_interStr != nil) {
		return [_interStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	}
	return nil;
}

//邮箱正则判定
+ (BOOL)isEmailAddress:(NSString*)email
{
    NSString *emailRegex = @"^\\w+((\\-\\w+)|(\\.\\w+))*@[A-Za-z0-9]+((\\.|\\-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+(BOOL)Isphonenumber:(NSString *)str{
    if (str.length != 11 || !([[str substringToIndex:2] isEqualToString:@"13"] ||[[str substringToIndex:2] isEqualToString:@"17"]|| [[str substringToIndex:2] isEqualToString:@"15"] || [[str substringToIndex:2] isEqualToString:@"18"] || [[str substringToIndex:2] isEqualToString:@"14"]) || [str rangeOfString:@"^[0-9\\-]*$" options:NSRegularExpressionSearch].location == NSNotFound) {
        
        return NO;
    }
    return YES;
    
}

+ (BOOL)validateCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}

@end
